/*******************************************************************************
 * 模块名:exti
 * 描述:外部中断函数
 * 作者:LUKE&Liu
 * 创建时间:2022/06/29 12:58:11
 ******************************************************************************/

#include <exti.h>
#include <led.h>

/*******************************************************************************
 * 函数名:delay_ms()
 * 代码描述:延时函数
 * 参数:ms,延时毫秒数
 * 作者:LUKE&Liu
 * 创建时间:2022/06/28 20:11:34
 ******************************************************************************/
void static delay_ms(unsigned int ms)
{
  unsigned short tmp;
  while (ms--)
  {
    for (tmp = 1000; tmp > 0; tmp--)
    {
    }
  }
}

/*******************************************************************************
 * 函数名:exit_init
 * 代码描述:外部中断初始化函数
 * 参数:无
 * 作者:LUKE&Liu
 * 创建时间:2022/06/29 13:18:18
 ******************************************************************************/
void exti_init(void)
{
  NVIC_InitTypeDef NVIC_InitStructure;
  EXTI_InitTypeDef EXTI_InitStructure;

  RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); //开启时钟

  SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOE, EXTI_PinSource3); //配置PE3引脚
  SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOE, EXTI_PinSource4); //配置PE4引脚

  EXTI_InitStructure.EXTI_Line = EXTI_Line3 | EXTI_Line4;
  EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
  EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
  EXTI_InitStructure.EXTI_LineCmd = ENABLE;
  EXTI_Init(&EXTI_InitStructure);

  NVIC_InitStructure.NVIC_IRQChannel = EXTI4_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x03;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x02;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  NVIC_InitStructure.NVIC_IRQChannel = EXTI3_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x02;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
}

/*******************************************************************************
 * 函数名:key_IRQHandler
 * 代码描述:按键中断服务函数
 * 参数:无
 * 作者:LUKE&Liu
 * 创建时间:2022/06/28 21:14:59
 ******************************************************************************/
void EXTI4_IRQHandler(void)
{
  delay_ms(50); //去除按键抖动
  if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_4) == 0)
  {
    led_turn_off(LED1);
  }
  EXTI_ClearITPendingBit(EXTI_Line4); //清楚中断标志
}

void EXTI3_IRQHandler(void)
{
  static char led_status = 0;
  delay_ms(50); //去除按键抖动
  if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_3) == 0)
  {
    led_status = !led_status;
  }
  if (led_status)
  {
    GPIO_ResetBits(GPIOA, GPIO_Pin_7);
  }
  else
  {
    GPIO_SetBits(GPIOA, GPIO_Pin_7);
  }
  EXTI_ClearITPendingBit(EXTI_Line3); //清楚中断标志
}
